package com.czk.shop.mq;

import com.alibaba.fastjson.JSON;
import com.comon.czk.constant.ShopCode;
import com.comon.czk.entity.MQEntity;
import com.czk.api.IUserService;
import com.czk.shop.pojo.TradeUserMoneyLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/10/20 21:23
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.order.topic}", consumerGroup = "${mq.order.consumer.group.name}", messageModel = MessageModel.BROADCASTING)
public class CancelMQListener implements RocketMQListener<MessageExt> {
    @Autowired
    private IUserService iUserService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            // 解析消息
            String body = new String(messageExt.getBody(), "UTF-8");
            log.info("接受到消息");
            MQEntity mqEntity = JSON.parseObject(body, MQEntity.class);
            if (mqEntity.getUserMoney() != null && mqEntity.getUserMoney().compareTo(BigDecimal.ZERO) > 0) {
                // 调用业务层进行余额修改
                TradeUserMoneyLog tradeUserMoneyLog = new TradeUserMoneyLog();
                tradeUserMoneyLog.setUseMoney(mqEntity.getUserMoney());
                tradeUserMoneyLog.setMoneyLogType(ShopCode.SHOP_USER_MONEY_REFUND.getCode());
                // userid
                tradeUserMoneyLog.setUserId(mqEntity.getUserId());
                // 订单id
                tradeUserMoneyLog.setOrderId(mqEntity.getOrderId());
                // 更新操作
                iUserService.updateMoneyPaid(tradeUserMoneyLog);
                log.info("余额退款成功");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("余额回退失败");
        }


    }
}
